package com.sixmac.controller.backend;

import com.sixmac.common.DataTableFactory;
import com.sixmac.controller.common.CommonController;
import com.sixmac.core.Constant;
import com.sixmac.entity.AppUser;
import com.sixmac.entity.Message;
import com.sixmac.entity.MessageInfo;
import com.sixmac.entity.WxUser;
import com.sixmac.service.*;
import com.sixmac.utils.DateUtils;
import com.sixmac.utils.JsonUtil;
import com.sixmac.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/30 0030.
 */
@Controller
@RequestMapping(value = "backend/message")
public class MessageController extends CommonController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageInfoService messageInfoService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private OperaService operaService;

    @RequestMapping("/index")
    public String index() {
        return "backend/消息列表";
    }

    @RequestMapping("/list")
    public void list(HttpServletResponse response,
                     Integer draw,
                     Integer start,
                     Integer length) {
        if (null == start || start == 0) {
            start = 1;
        }
        int pageNum = getPageNum(start, length);

        Page<Message> page = messageService.find(pageNum, length);

        Map<String, Object> result = DataTableFactory.fitting(draw, page);
        WebUtil.printJson(response, result);
    }

    @RequestMapping("/show")
    public String info(ModelMap model, Integer id) {
        if (null != id) {
            Message message = messageService.getById(id);
            if (null != message) {
                List<MessageInfo> list = messageInfoService.findListByMessageId(id);
                StringBuffer sb = new StringBuffer("");
                for (MessageInfo messageInfo : list) {
                    sb.append(messageInfo.getUserId() + ",");
                }

                model.addAttribute("ids", sb.length() > 0 ? (sb.toString().substring(0, sb.length() - 1)) : "");
            }
            model.addAttribute("message", message);
        }

        return "backend/消息详情";
    }

    @RequestMapping("/save")
    @ResponseBody
    public Integer save(HttpServletRequest request,
                        Integer id,
                        String name,
                        String content,
                        String sendTime,
                        Integer type,
                        String[] appUser,
                        String[] wxUser) {
        try {
            Message message = null;

            if (!DateUtils.dateCompare(DateUtils.stringToDateWithFormat(sendTime, "yyyy-MM-dd hh:mm:ss"))) {
                return -1;
            }

            if (null == id) {
                message = new Message();
                message.setCreateTime(new Date());
                message.setStatus(Constant.MESSAGE_STATUS_000);
            } else {
                message = messageService.getById(id);
                // 当消息的状态为已撤回时，将消息状态更改为待发送
                if (message.getStatus() == Constant.MESSAGE_STATUS_002) {
                    message.setStatus(Constant.MESSAGE_STATUS_000);
                    message.setSendTime(null);
                }
            }

            message.setName(name);
            message.setContent(content);
            message.setType(type);
            if (null != sendTime) {
                message.setSendTime(DateUtils.stringToDateWithFormat(sendTime, "yyyy-MM-dd hh:mm:ss"));
            }

            messageService.update(message);

            // 删除消息详情
            messageInfoService.deleteByMessageId(message.getId());

            // 保存消息详情
            List<MessageInfo> list = new ArrayList<MessageInfo>();
            switch (type) {
                case 1:
                    // 全部
                    List<MessageInfo> wxUserList = getWxUserMessageList(message, wxUserService.findList(""));
                    for (MessageInfo messageInfo : wxUserList) {
                        list.add(messageInfo);
                    }
                    List<MessageInfo> appUserList = getAppUserMessageList(message, appUserService.findList(""));
                    for (MessageInfo messageInfo : appUserList) {
                        list.add(messageInfo);
                    }
                    break;
                case 2:
                    // 微信用户
                    WxUser tempWxUser = null;
                    List<WxUser> wxUserListPlus = new ArrayList<WxUser>();

                    for (String idStr : wxUser) {
                        tempWxUser = wxUserService.getById(Integer.parseInt(idStr));
                        wxUserListPlus.add(tempWxUser);
                    }

                    List<MessageInfo> wxUserList2 = getWxUserMessageList(message, wxUserListPlus);
                    for (MessageInfo messageInfo : wxUserList2) {
                        list.add(messageInfo);
                    }
                    break;
                case 3:
                    // APP用户
                    AppUser tempAppUser = null;
                    List<AppUser> appUserListPlus = new ArrayList<AppUser>();

                    for (String idStr : appUser) {
                        tempAppUser = appUserService.getById(Integer.parseInt(idStr));
                        appUserListPlus.add(tempAppUser);
                    }

                    List<MessageInfo> appUserList2 = getAppUserMessageList(message, appUserListPlus);
                    for (MessageInfo messageInfo : appUserList2) {
                        list.add(messageInfo);
                    }
                    break;
            }

            messageInfoService.sendMessageOnTime(message.getSendTime(), list, message.getStatus() == Constant.MESSAGE_STATUS_000);

            operaService.addOperaInfo(request, (null == id ? "添加" : "修改") + "消息 " + message.getName());

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Integer update(HttpServletRequest request, Integer id, Integer status) {
        try {
            Message message = messageService.getById(id);
            if (status == Constant.MESSAGE_STATUS_001) {
                message.setSendTime(new Date());
            }
            message.setStatus(status);
            messageService.update(message);

            operaService.addOperaInfo(request, "将消息 " + message.getName() + " 状态更改为 " + (message.getStatus() == Constant.MESSAGE_STATUS_001 ? "已发送" : "已撤回"));

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Integer delete(HttpServletRequest request, Integer id) {
        try {
            Message message = messageService.getById(id);

            operaService.addOperaInfo(request, "删除消息 " + message.getName());

            messageService.deleteById(id);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 删除信息
     *
     * @param ids
     * @return
     */
    @RequestMapping("/batchDel")
    @ResponseBody
    public Integer batchDel(HttpServletRequest request, String ids) {
        try {
            int[] arrayId = JsonUtil.json2Obj(ids, int[].class);
            messageService.deleteAll(request, arrayId);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 拼接微信用户消息列表
     *
     * @param message
     * @param wxUserList
     * @return
     */
    public List<MessageInfo> getWxUserMessageList(Message message, List<WxUser> wxUserList) {
        MessageInfo messageInfo = null;
        List<MessageInfo> list = new ArrayList<MessageInfo>();

        for (WxUser tempWxUser : wxUserList) {
            messageInfo = new MessageInfo();
            messageInfo.setMessage(message);
            messageInfo.setType(2);
            messageInfo.setUserId(tempWxUser.getId());

            list.add(messageInfo);
        }

        return list;
    }

    /**
     * 拼接app用户消息列表
     *
     * @param message
     * @param appUserList
     * @return
     */
    public List<MessageInfo> getAppUserMessageList(Message message, List<AppUser> appUserList) {
        MessageInfo messageInfo = null;
        List<MessageInfo> list = new ArrayList<MessageInfo>();

        for (AppUser tempAppUser : appUserList) {
            messageInfo = new MessageInfo();
            messageInfo.setMessage(message);
            messageInfo.setType(3);
            messageInfo.setUserId(tempAppUser.getId());

            list.add(messageInfo);
        }

        return list;
    }
}
